package com.ricchieri.lazymodel;

import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.filter.CharterExpenseFilter;
import com.ricchieri.model.CharterExpense;
import com.ricchieri.service.interf.ICharterExpenseService;

public class CharterExpenseLazyDataModel extends LazyDataModel<CharterExpense> {
	
	private static final long serialVersionUID = 4597910900120000180L;
	
	private List <CharterExpense> charterExpenses;
	private CharterExpenseFilter charterExpensesFilter;
	private ICharterExpenseService charterExpenseService;
	
	public CharterExpenseLazyDataModel(ICharterExpenseService charterService, CharterExpenseFilter charterFilter) {
		super();
		this.charterExpensesFilter = charterFilter;
		this.charterExpenseService = charterService;
	}
	
	@Override
	public List<CharterExpense> load(int startingAt, int maxPerPage, String sortField, 
			SortOrder sortOrder, Map<String, String> filters) {
		
		charterExpensesFilter.setSortField(sortField);
		charterExpensesFilter.setSortOrder(sortOrder.toString());
		
        if(getRowCount() <= 0) {
            setRowCount(getCharterExpenseService().getAllCharterExpenseCountByFilter(charterExpensesFilter));
        }
        
        if(getRowCount() == startingAt && getRowCount()  != 0) {
        	startingAt = startingAt - BusinessSettings.ROW_MAX_RESULT;
        }
        charterExpenses = getCharterExpenseService().getAllCharterExpensePaginatedByFilter(charterExpensesFilter, startingAt);

        setPageSize(BusinessSettings.ROW_MAX_RESULT);
        
        return charterExpenses;
	}
	
    @Override
    public Object getRowKey(CharterExpense charter) {
        return charter.getId();
    }

    @Override
    public CharterExpense getRowData(String charterId) {
        int id = Integer.valueOf(charterId);

        for (CharterExpense charterExpense : charterExpenses) {
            if(id == charterExpense.getId()) {
                return charterExpense;
            }
        }
        return null;
    }

	public List<CharterExpense> getCharterExpenses() {
		return charterExpenses;
	}

	public void setCharterExpenses(List<CharterExpense> charterExpenses) {
		this.charterExpenses = charterExpenses;
	}

	public CharterExpenseFilter getCharterExpensesFilter() {
		return charterExpensesFilter;
	}

	public void setCharterExpensesFilter(CharterExpenseFilter charterExpensesFilter) {
		this.charterExpensesFilter = charterExpensesFilter;
	}

	public ICharterExpenseService getCharterExpenseService() {
		return charterExpenseService;
	}

	public void setCharterExpenseService(
			ICharterExpenseService charterExpenseService) {
		this.charterExpenseService = charterExpenseService;
	}
}